<template>
  <div class="provider-manage">
    <!-- 查询区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form" @submit.prevent>
      <el-form-item label="供应商名称">
        <el-input v-model="searchForm.providerName" placeholder="请输入供应商名称" clearable />
      </el-form-item>
      <el-form-item label="企业类型">
        <el-select v-model="searchForm.companyType" placeholder="请选择企业类型" clearable>
          <el-option label="国有企业" value="国有企业" />
          <el-option label="民营企业" value="民营企业" />
          <el-option label="外资企业" value="外资企业" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态">
        <el-select v-model="searchForm.auditStatus" placeholder="请选择审核状态" clearable>
          <el-option label="未审核" :value="0" />
          <el-option label="已通过" :value="1" />
          <el-option label="未通过" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="评级">
        <el-select v-model="searchForm.rating" placeholder="请选择评级" clearable>
          <el-option label="A级" value="A" />
          <el-option label="B级" value="B" />
          <el-option label="C级" value="C" />
          <el-option label="D级" value="D" />
        </el-select>
      </el-form-item>
      <el-form-item label="成立年份">
        <el-date-picker v-model="searchForm.establishedYearRange" type="daterange" range-separator="-"
          start-placeholder="开始年份" end-placeholder="结束年份" value-format="YYYY" :picker-options="{ type: 'year' }" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 供应商列表 -->
    <el-table :data="providerList" border>
      <el-table-column prop="providerId" label="供应商编号" min-width="100" />
      <el-table-column prop="providerName" label="供应商名称" min-width="120" />
      <el-table-column prop="factoryAddress" label="厂址" min-width="150" />
      <el-table-column prop="principalName" label="负责人姓名" min-width="100" />
      <el-table-column prop="principalPhone" label="负责人联系电话" min-width="120">
        <template #default="{ row }">{{ row.principalPhone || '-' }}</template>
      </el-table-column>
      <el-table-column prop="companyType" label="企业类型" min-width="100" />
      <el-table-column prop="registeredCapital" label="注册资本" min-width="100" />
      <el-table-column prop="employeeCount" label="员工人数" min-width="100" />
      <el-table-column prop="establishedYear" label="成立年份" min-width="100" />
      <el-table-column prop="rating" label="评级" min-width="80">
        <template #default="{ row }">
          <el-tag :type="ratingType[row.rating || 'A']">
            {{ row.rating || 'A' }}级
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="auditStatus" label="审核状态" min-width="100">
        <template #default="{ row }">
          <el-tag :type="statusType[row.auditStatus]">
            {{ statusMap[row.auditStatus] || '未审核' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isActive" label="状态" min-width="80">
        <template #default="{ row }">
          <el-tag :type="row.isActive ? 'success' : 'danger'">
            {{ row.isActive ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" :min-width="isAdmin ? 300 : 155">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleEditProvider(row)">修改</el-button>
          <el-button v-if="row.auditStatus === 1 && isAdmin" size="small" type="danger"
            @click="handleDeleteProvider(row.providerId)">删除</el-button>
          <el-button v-if="row.auditStatus === 1 && isPrime" size="small" type="warning" @click="handleComplaint(row)">
            投诉
          </el-button>
          <el-button v-if="row.auditStatus === 1 && isAdmin" size="small" type="info" @click="handleRating(row)">
            评级
          </el-button>
          <el-button v-if="row.auditStatus === 1 && isAdmin" size="small" :type="row.isActive ? 'danger' : 'success'"
            @click="toggleActive(row)">
            {{ row.isActive ? '禁用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination background layout="prev, pager, next, jumper, ->, total" :total="pagination.total"
      :page-size="pagination.size" :current-page="pagination.current" @current-change="handlePageChange" />

    <!-- 添加供应商对话框 -->
    <el-dialog :title="editProviderId ? '修改供应商' : '添加供应商'" v-model="showAddDialog">
      <el-form :model="addForm" label-width="100px" :rules="formRules">
        <el-form-item label="供应商名称" prop="providerName">
          <el-input v-model="addForm.providerName" />
        </el-form-item>
        <el-form-item label="厂址" prop="factoryAddress">
          <el-input v-model="addForm.factoryAddress" />
        </el-form-item>
        <el-form-item label="负责人姓名" prop="principalName">
          <el-input v-model="addForm.principalName" />
        </el-form-item>
        <el-form-item label="负责人电话" prop="principalPhone">
          <el-input v-model="addForm.principalPhone" placeholder="请输入11位手机号" />
        </el-form-item>
        <el-form-item label="企业类型" prop="companyType">
          <el-select v-model="addForm.companyType" placeholder="请选择企业类型">
            <el-option label="国有企业" value="国有企业" />
            <el-option label="民营企业" value="民营企业" />
            <el-option label="外资企业" value="外资企业" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册资本" prop="registeredCapital">
          <el-input v-model="addForm.registeredCapital" type="number" />
        </el-form-item>
        <el-form-item label="员工人数" prop="employeeCount">
          <el-input v-model="addForm.employeeCount" type="number" />
        </el-form-item>
        <el-form-item label="成立年份" prop="establishedYear">
          <el-date-picker v-model="addForm.establishedYear" type="year" placeholder="选择年份" value-format="YYYY"
            style="width: 100%;" />
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="addForm.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false; editProviderId = null">取消</el-button>
        <el-button type="primary" @click="handleSubmitProvider">确定</el-button>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog title="供应商审核" v-model="showAuditDialog">
      <el-form :model="auditForm" label-width="100px">
        <el-form-item label="供应商名称">
          <span>{{ currentProvider?.providerName }}</span>
        </el-form-item>
        <el-form-item label="审核结果" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :value="1">通过</el-radio>
            <el-radio :value="2">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="auditComment">
          <el-input v-model="auditForm.auditComment" type="textarea" :rows="3" placeholder="请输入审核意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAuditDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 投诉对话框 -->
    <el-dialog title="供应商投诉" v-model="showComplaintDialog">
      <el-form :model="complaintForm" label-width="100px" :rules="complaintRules">
        <el-form-item label="供应商名称">
          <span>{{ currentProvider?.providerName }}</span>
        </el-form-item>
        <el-form-item label="投诉类型" prop="complaintType">
          <el-select v-model="complaintForm.complaintType" placeholder="请选择投诉类型">
            <el-option label="质量问题" value="质量问题" />
            <el-option label="交付延迟" value="交付延迟" />
            <el-option label="服务态度" value="服务态度" />
            <el-option label="价格争议" value="价格争议" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="投诉内容" prop="complaintContent">
          <el-input v-model="complaintForm.complaintContent" type="textarea" :rows="3" placeholder="请详细描述投诉内容" />
        </el-form-item>
        <el-form-item label="严重程度" prop="severity">
          <el-rate v-model="complaintForm.severity" :texts="['轻微', '一般', '中等', '严重', '极其严重']" show-text />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showComplaintDialog = false">取消</el-button>
        <el-button type="primary" @click="submitComplaint">提交投诉</el-button>
      </template>
    </el-dialog>

    <!-- 评级对话框 -->
    <el-dialog title="供应商评级调整" v-model="showRatingDialog">
      <!-- 投诉历史记录卡片 -->
      <el-card class="box-card" style="margin-bottom: 20px">
        <template #header>
          <div class="card-header">
            <span>历史投诉记录</span>
            <el-button type="text" @click="loadComplaintHistory">
              <el-icon>
                <Refresh />
              </el-icon> 刷新
            </el-button>
          </div>
        </template>
        <el-table :data="complaintHistory" height="200" v-loading="loadingComplaints">
          <el-table-column prop="complaintTime" label="投诉时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.complaintTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="complaintType" label="类型" width="120" />
          <el-table-column prop="severity" label="严重程度" width="100">
            <template #default="scope">
              <el-rate v-model="scope.row.severity" disabled show-score />
            </template>
          </el-table-column>
          <el-table-column prop="complaintContent" label="投诉内容" min-width="200" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 0 ? 'warning' : 'success'">
                {{ scope.row.status === 0 ? '未处理' : '已处理' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-form :model="ratingForm" label-width="100px" :rules="ratingRules">
        <el-form-item label="供应商名称">
          <span>{{ currentProvider?.providerName }}</span>
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="ratingForm.status" placeholder="请选择处理状态">
            <el-option label="已处理" value="1" />
            <el-option label="未处理" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理结果" prop="result">
          <el-input v-model="ratingForm.result" type="textarea" :rows="3" placeholder="请输入处理结果" />
        </el-form-item>
        <el-form-item label="当前评级">
          <el-tag :type="ratingType[currentProvider?.rating || 'A']">
            {{ currentProvider?.rating || 'A' }}级
          </el-tag>
        </el-form-item>
        <el-form-item label="新评级" prop="rating">
          <el-select v-model="ratingForm.rating" placeholder="请选择新评级">
            <el-option label="A级" value="A" />
            <el-option label="B级" value="B" />
            <el-option label="C级" value="C" />
            <el-option label="D级" value="D" />
          </el-select>
        </el-form-item>
        <el-form-item label="调整原因" prop="reason">
          <el-input v-model="ratingForm.reason" type="textarea" :rows="3" placeholder="请输入评级调整原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRatingDialog = false">取消</el-button>
        <el-button type="primary" @click="submitRating">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios';
import { formatDateTime } from '@/utils/format' // 创建这个工具函数
import { Refresh } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

// 添加响应式数据
const complaintHistory = ref([])
const loadingComplaints = ref(false)

// 添加加载投诉历史记录的方法
const loadComplaintHistory = async () => {
  if (!currentProvider.value?.providerId) return

  loadingComplaints.value = true
  try {
    // 添加错误调试信息
    console.log('Loading complaints for provider:', currentProvider.value.providerId)

    const res = await axios.get(
      import.meta.env.VITE_API_URL + 'provider/complaints/' + currentProvider.value.providerId, // 简化URL，让axios配置处理基础URL
      {
        params: {
          pageNum: 1,
          pageSize: 10
        }
      }
    )


    // 添加响应数据调试信息
    console.log('Complaints response:', res.data)

    if (res.data && res.data.records) {
      complaintHistory.value = res.data.records
    } else {
      console.error('Invalid response format:', res.data)
      ElMessage.warning('获取投诉记录格式异常')
    }
  } catch (error) {
    console.error('Load complaints error:', error)
    ElMessage.error(`加载投诉历史失败: ${error.message}`)
  } finally {
    loadingComplaints.value = false
  }
}

// 状态映射
const statusMap = {
  0: '未审核',
  1: '已通过',
  2: '未通过'
}

const statusType = {
  0: 'warning',
  1: 'success',
  2: 'danger'
}

// 评级映射
const ratingType = {
  'A': 'success',
  'B': 'info',
  'C': 'warning',
  'D': 'danger'
}


// 从Pinia获取用户信息
const userStore = useUserStore()
// 权限控制
const userTitle = computed(() => userStore.userInfo?.title || '普通操作人员')
const isAdmin = computed(() => ['部门经理'].includes(userTitle.value))
const isPrime = computed(() => ['普通操作人员'].includes(userTitle.value))
const currentUser = computed(() => userStore.userInfo)

const searchForm = reactive({
  providerName: '',
  companyType: '',
  auditStatus: null,
  rating: null,
  establishedYearRange: [],
})

const addForm = reactive({
  providerName: '',
  factoryAddress: '',
  principalName: '',
  principalPhone: '',
  companyType: '',
  registeredCapital: '',
  employeeCount: '',
  establishedYear: '',
  description: ''
})

const formRules = reactive({
  providerName: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
  companyType: [{ required: true, message: '请选择企业类型', trigger: 'change' }],
  principalPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
})

const providerList = ref([])
const pagination = reactive({
  total: 0,
  size: 10,
  current: 1
})
const showAddDialog = ref(false)
const editProviderId = ref<number | null>(null)

// 审核相关
const showAuditDialog = ref(false)
const currentProvider = ref(null)
const auditForm = reactive({
  providerId: null,
  auditStatus: 1,
  auditComment: '',
  auditorId: computed(() => currentUser.value?.id || null) // 从当前登录用户获取ID
})

// 投诉相关
const showComplaintDialog = ref(false)
const complaintForm = reactive({
  providerId: null,
  complaintType: '',
  complaintContent: '',
  severity: 3,
  complainantId: computed(() => currentUser.value?.id || null) // 从当前登录用户获取ID
})

const complaintRules = reactive({
  complaintType: [{ required: true, message: '请选择投诉类型', trigger: 'change' }],
  complaintContent: [{ required: true, message: '请输入投诉内容', trigger: 'blur' }],
  severity: [{ required: true, message: '请选择严重程度', trigger: 'change' }]
})

// 评级相关
const showRatingDialog = ref(false)
const ratingForm = reactive({
  providerId: null,
  rating: '',
  reason: '',
  status: '',  // 处理状态
  result: '',   // 处理结果
  operatorId: computed(() => currentUser.value?.id || null) // 从当前登录用户获取ID
})

const ratingRules = reactive({
  rating: [{ required: true, message: '请选择新评级', trigger: 'change' }],
  reason: [{ required: true, message: '请输入评级调整原因', trigger: 'blur' }],
  status: [{ required: true, message: '请选择处理状态', trigger: 'change' }],
  result: [{ required: true, message: '请输入处理结果', trigger: 'blur' }]
})

const handleAudit = (row) => {
  currentProvider.value = row
  auditForm.providerId = row.providerId
  auditForm.auditStatus = 1
  auditForm.auditComment = ''
  showAuditDialog.value = true
}

const submitAudit = async () => {
  try {
    const params = new URLSearchParams()
    params.append('providerId', auditForm.providerId)
    params.append('auditStatus', auditForm.auditStatus)
    params.append('auditComment', auditForm.auditComment)
    params.append('auditorId', auditForm.auditorId)

    await axios.post(
      import.meta.env.VITE_API_URL + 'provider/audit',
      params
    )

    ElMessage.success('审核成功')
    showAuditDialog.value = false
    fetchProviders(pagination.current)
  } catch (e) {
    ElMessage.error('审核失败')
  }
}

// 投诉处理
const handleComplaint = (row) => {
  currentProvider.value = row
  complaintForm.providerId = row.providerId
  complaintForm.complaintType = row.complaintType
  complaintForm.complaintContent = row.complaintContent
  complaintForm.severity = row.severity
  showComplaintDialog.value = true
}

const submitComplaint = async () => {
  try {
    await axios.post(
      import.meta.env.VITE_API_URL + 'provider/complaint',
      complaintForm
    )

    ElMessage.success('投诉提交成功')
    showComplaintDialog.value = false
    fetchProviders(pagination.current)
  } catch (e) {
    ElMessage.error('投诉提交失败')
  }
}

// 评级处理
const handleRating = (row) => {
  currentProvider.value = row
  ratingForm.providerId = row.providerId
  ratingForm.rating = row.rating || 'A'
  ratingForm.reason = ''
  showRatingDialog.value = true

  // 加载投诉历史
  loadComplaintHistory()
}


const submitRating = async () => {
  try {
    await axios.post(
      import.meta.env.VITE_API_URL + 'provider/updateRating',
      {
        ...ratingForm,
        providerId: currentProvider.value?.providerId,
        processTime: new Date().toISOString() // 添加处理时间
      }
    )

    ElMessage.success('评级调整成功')
    showRatingDialog.value = false
    fetchProviders(pagination.current)
  } catch (e) {
    ElMessage.error('评级调整失败')
  }
}

// 启用/禁用供应商
const toggleActive = async (row) => {
  try {
    await axios.post(
      import.meta.env.VITE_API_URL + 'provider/toggleActive',
      { providerId: row.providerId, isActive: !row.isActive }
    )

    ElMessage.success(row.isActive ? '供应商已禁用' : '供应商已启用')
    fetchProviders(pagination.current)
  } catch (e) {
    ElMessage.error('操作失败')
  }
}

const fetchProviders = async (pageNum = 1) => {
  try {
    const params = {
      providerName: searchForm.providerName || null,
      companyType: searchForm.companyType || null,
      auditStatus: 1, // 固定为已审核通过
      rating: searchForm.rating,
      establishedYearBegin: searchForm.establishedYearRange?.[0] || null,
      establishedYearEnd: searchForm.establishedYearRange?.[1] || null
    }
    const res = await axios.post(
      import.meta.env.VITE_API_URL + `provider/page?pageNum=${pageNum}&pageSize=${pagination.size}`,
      params
    )
    console.log(res);

    providerList.value = res.data.records
    pagination.total = res.data.total
    pagination.current = res.data.current
    pagination.size = res.data.size
  } catch (e) {
    ElMessage.error('获取供应商数据失败')
  }
}

const handleEditProvider = (row: any) => {
  Object.assign(addForm, row)
  editProviderId.value = row.providerId
  showAddDialog.value = true
}

const handleDeleteProvider = async (providerId: number) => {
  try {
    await axios.delete(import.meta.env.VITE_API_URL + `provider/${providerId}`)
    ElMessage.success('删除成功')
    fetchProviders(1)
  } catch (e) {
    ElMessage.error('删除失败')
  }
}

const handleSubmitProvider = async () => {
  try {
    const url = editProviderId.value
      ? import.meta.env.VITE_API_URL + 'provider/update'
      : import.meta.env.VITE_API_URL + 'provider/save'

    await axios.post(url, {
      ...addForm,
      providerId: editProviderId.value
    })

    ElMessage.success(editProviderId.value ? '修改成功' : '添加成功')
    showAddDialog.value = false
    editProviderId.value = null
    await fetchProviders(1)
  } catch (e) {
    ElMessage.error(editProviderId.value ? '修改失败' : '添加失败')
  }
}

const handleSearch = () => fetchProviders(1)
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    if (Array.isArray(searchForm[key])) {
      searchForm[key] = []
    } else {
      searchForm[key] = null
    }
  })
  fetchProviders(1)
}
const handlePageChange = (page: number) => fetchProviders(page)

onMounted(() => {
  fetchProviders(1)
})

</script>

<style scoped>
@import '@/styles/views.css';

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  margin-bottom: 20px;
}
</style>